﻿// ———————————————————————–
// <copyright file="DateTimeRange.cs" company="The MITRE Corporation">
//    Copyright (c) 2014 The MITRE Corporation. All rights reserved.
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//    http://www.apache.org/licenses/LICENSE-2.0
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
// </copyright>
// ———————————————————————–
/////////////////////////////////////////////////////////////////////////////////////////////////
// DateTimeRange.cs:
//
// Represents a range of dates
//
// Project: IC.NET - CAD Library
// Author:  Jim Cronin - MITRE
/////////////////////////////////////////////////////////////////////////////////////////////////

// Copyright (c) 2014 The MITRE Corporation. All rights reserved.
//
// NOTICE
// This software was produced for the U. S. Government
// under Contract No. FA8721-09-C-0001, and is
// subject to the Rights in Noncommercial Computer Software
// and Noncommercial Computer Software Documentation Clause
// (DFARS) 252.227-7014 (JUN 1995)

using System;
using System.Xml;
using EDXLSharp.NIEMCore;

namespace EDXLSharp.NIEMCADLib
{
  /// <summary>
  /// A representation of a range of time
  /// </summary>
  public class EventValidityDateTimeRange : ComplexTypeBase
  {
    /// <summary>
    /// The beginning of the time range
    /// </summary>
    public DateTime StartDate { get; set; }

    /// <summary>
    /// The end of the time range
    /// </summary>
    public DateTime EndDate { get; set; }

    /// <summary>
    /// Initializes a new DateTimeRange given the start and end of the range
    /// </summary>
    /// <param name="start">Beginning of the range</param>
    /// <param name="end">End of the range</param>
    /// <exception cref="System.ArgumentException">Thrown if end is earlier than start</exception>
    public EventValidityDateTimeRange(DateTime start, DateTime end)
    {
      if (end.CompareTo(start) < 0)
      {
        throw new ArgumentException("Invalid arguments 'start' and 'end'. DateTime 'end' must be later than 'start'");
      }

      StartDate = start;
      EndDate = end;
    }

    public override string ElementName
    {
      get { return "EventValidityDateTimeRange"; }
    }

    public override string ElementNamespace
    {
      get { return EDXLConstants.MilopsNamespace; }
    }

    public override string ElementPrefix
    {
      get { return EDXLConstants.MilopsPrefix; }
    }

    /// <summary>
    /// Generates a date time range wtih default min/max values.
    /// </summary>
    public EventValidityDateTimeRange()
    {
      StartDate = DateTime.MinValue;
      EndDate = DateTime.MaxValue;
    }

    /// <summary>
    /// Initializes a new DateTimeRange from a DateTimeRange XML node
    /// </summary>
    /// <param name="node">Xml node</param>
    /// <exception cref="System.ArgumentNullException">Thrown if rootnode is null</exception>
    /// <exception cref="System.ArgumentException">Thrown if rootnode is not an EventValidityDateTimeRange element</exception>
    /// <exception cref="EDXLSharp.NIEMCADLib.ValidationException">Thrown if EndDate is befre StartDate</exception>
    public EventValidityDateTimeRange(XmlNode node)
    {
      this.ReadXML(node);
    }

    /// <summary>
    /// Writes this Object to an inline XML Document
    /// </summary>
    /// <param name="xwriter">Valid XMLWriter</param>
    /// <exception cref="System.ArgumentNullException">Thrown if xwriter is null</exception>
    /// <exception cref="EDXLSharp.NIEMCADLib.ValidationException">Thrown if EndDate is befre StartDate</exception>
    public override void WriteXML(XmlWriter xwriter)
    {
      if (xwriter == null)
      {
        throw new ArgumentNullException("xwriter");
      }

      this.Validate();

      xwriter.WriteStartElement(this.ElementPrefix, this.ElementName, this.ElementNamespace);
      xwriter.WriteStartElement(EDXLConstants.NiemCorePrefix, "StartDate", EDXLConstants.NiemCoreNamespace);
      xwriter.WriteElementString(EDXLConstants.NiemCorePrefix, "DateTime", EDXLConstants.NiemCoreNamespace, this.StartDate.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.ffZ"));
      xwriter.WriteEndElement();
      xwriter.WriteStartElement(EDXLConstants.NiemCorePrefix, "EndDate", EDXLConstants.NiemCoreNamespace);
      xwriter.WriteElementString(EDXLConstants.NiemCorePrefix, "DateTime", EDXLConstants.NiemCoreNamespace, this.EndDate.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.ffZ"));
      xwriter.WriteEndElement();
      xwriter.WriteEndElement();
    }

    /// <summary>
    /// Reads this Object's values from an XML NodeList
    /// </summary>
    /// <param name="rootnode">Root XML Node of the Object Element</param>
    /// <exception cref="System.ArgumentNullException">Thrown if rootnode is null</exception>
    /// <exception cref="System.ArgumentException">Thrown if rootnode is not an EventValidityDateTimeRange element</exception>
    /// <exception cref="EDXLSharp.NIEMCADLib.ValidationException">Thrown if EndDate is befre StartDate</exception>
    public override void ReadXML(XmlNode rootnode)
    {
      if (rootnode == null)
      {
        throw new ArgumentNullException("rootnode");
      }
      if (rootnode.LocalName != this.ElementName)
      {
        throw new ArgumentException("Not an EventValidityDateTimeRange element");
      }

      foreach (XmlNode node in rootnode.ChildNodes)
      {
        if (node.ChildNodes.Count != 1)
        {
          throw new ArgumentException("StartDate and EndDate should have exactly one child");
        }
        if (node.FirstChild.LocalName != "DateTime")
        {
          throw new ArgumentException("StartDate's and EndDate's child should be DateTime");
        }

        try
        {
          switch (node.LocalName)
          {
            case "StartDate":
              if (this.StartDate != DateTime.MinValue)
              {
                throw new ArgumentException("There should only be a single start date element");
              }
              this.StartDate = DateTime.Parse(node.InnerText);
              break;
            case "EndDate":
              if (this.EndDate != DateTime.MaxValue)
              {
                throw new ArgumentException("There should only be a single end date element");
              }
              this.EndDate = DateTime.Parse(node.InnerText);
              break;
            default:
              throw new ArgumentException("Invalid child element " + node.LocalName);
          }
        }
        catch (FormatException e)
        {
          throw new ArgumentException("The date string given was not in an apporpriate date format.", e);
        }
      }

      this.Validate();
    }

    /// <summary>
    /// Validates the range
    /// </summary>
    /// <exception cref="EDXLSharp.ValidationException">Thrown if EndDate is befre StartDate</exception>
    public override void Validate()
    {
      if (StartDate == DateTime.MinValue)
      {
        throw new ValidationException("There must be a valid start date.");
      }

      if (EndDate == DateTime.MaxValue)
      {
        throw new ValidationException("There must be a valid end date.");
      }
      if (EndDate.CompareTo(StartDate) < 0)
      {
        throw new ValidationException("The EndDate must be later than the StartDate");
      }
    }
  }
}
